package com.example.learningnote.services;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.util.Random;

public class LocationService extends Service {
    private static final String TAG = "LocationService";
    private final IBinder binder = new LocalBinder();
    private Handler handler = new Handler();
    private boolean isTracking = false;
    private double latitude = 0.0;
    private double longitude = 0.0;
    private Random random = new Random();

    public class LocalBinder extends Binder {
        public LocationService getService() {
            return LocationService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Created");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "Service Bound");
        startLocationTracking();
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "Service Unbound");
        stopLocationTracking();
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service Destroyed");
        stopLocationTracking();
    }

    private void startLocationTracking() {
        if (!isTracking) {
            isTracking = true;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (isTracking) {
                        // 模拟位置更新
                        latitude += random.nextDouble() * 0.001;
                        longitude += random.nextDouble() * 0.001;
                        Log.d(TAG, "Location: (" + latitude + ", " + longitude + ")");
                        handler.postDelayed(this, 2000); // 每 2 秒更新
                    }
                }
            });
        }
    }

    private void stopLocationTracking() {
        isTracking = false;
        handler.removeCallbacksAndMessages(null);
    }

    // 提供给客户端的方法
    public double getLatitude() {
        return latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getDistance() {
        // 模拟计算移动距离（实际中可使用 Location.distanceTo）
        return random.nextDouble() * 10; // 返回 0-10 米的随机距离
    }
}

